package com.vm.osm.business.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonObject;
import com.vm.osm.business.common.Constants;
import com.vm.osm.business.dao.*;
import com.vm.osm.business.dto.CreateNotifyReq;
import com.vm.osm.business.dto.rsp.authRule.DispatchRule;
import com.vm.osm.business.dto.rsp.authRule.RspRulePage;
import com.vm.osm.business.entity.OsmDispatchRelaStaff;
import com.vm.osm.business.entity.OsmDispatchRule;
import com.vm.osm.business.entity.OsmOrderFailure;
import com.vm.osm.business.entity.OsmSysConfig;
import com.vm.osm.business.service.IOsmDispatchRuleService;
import com.vm.osm.business.util.GsonUtil;
import com.vm.osm.business.util.NotifyUtil;
import com.vm.osm.business.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by chenzui on 2018/2/23.
 */
@Service
public class OsmDispatchRuleServiceImpl implements IOsmDispatchRuleService {
    @Autowired
    private OsmOrderFailureMapper osmOrderFailureMapper;

    @Autowired
    private OsmDispatchRuleMapper osmDispatchRuleMapper;

    @Autowired
    private OsmSysConfigMapper osmSysConfigMapper;

    @Autowired
    private OsmDispatchRelaStaffMapper osmDispatchRelaStaffMapper;

    @Autowired
    private NotifyUtil notifyUtil;

    @Override
    public int deleteByPrimaryKey(String id) {
        return osmDispatchRuleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(OsmDispatchRule record) {
        return osmDispatchRuleMapper.insert(record);
    }

    @Override
    public int insertSelective(OsmDispatchRule record) {
        return osmDispatchRuleMapper.insertSelective(record);
    }

    @Override
    public OsmDispatchRule selectByPrimaryKey(String id) {
        return osmDispatchRuleMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(OsmDispatchRule record) {
        return osmDispatchRuleMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(OsmDispatchRule record) {
        return osmDispatchRuleMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<DispatchRule> getDispatchesByCond(String type, String objId,String authMan,String authObjName,String enterpriseId) {
        return osmDispatchRuleMapper.getDispatchesByCond(type,objId,authMan,authObjName,enterpriseId);
    }
    @Transactional
    @Override
    public void orderAutoDispatch(String orderId) {
        OsmOrderFailure order = osmOrderFailureMapper.selectByPrimaryKey(orderId);

        //抢单开关是否开启
        OsmSysConfig dispatch =  osmSysConfigMapper.queryByCfgCode(Constants.CFG_CODE_DISPATCH,order.getEnterpriseId());
        //是否满足一个条件就可以抢
        OsmSysConfig condition = osmSysConfigMapper.queryByCfgCode(Constants.CFG_CODE_CONDITION,order.getEnterpriseId());


        String openStatus = dispatch!=null?dispatch.getStatus().toString():"0";

        String conditionStatus = condition!=null?condition.getStatus().toString():"0";

        if("1".equals(openStatus)){

            osmOrderFailureMapper.updateByPrimaryKeySelective(order);

            String departmentId = order.getDepartmentId();

            String failTypeId = order.getFailTypeId();

            String deviceTypeId = order.getDeviceTypeId();

            List<DispatchRule> ruleForDepartment = osmDispatchRuleMapper.getDispatchesByCond(Constants.AUTH_BY_BU_MEN,departmentId,null,null,order.getEnterpriseId());

            List<DispatchRule> ruleForFailType = osmDispatchRuleMapper.getDispatchesByCond(Constants.AUTH_BY_FAIL_TYPE,failTypeId,null,null,order.getEnterpriseId());

            List<DispatchRule> ruleForDeviceType = osmDispatchRuleMapper.getDispatchesByCond(Constants.AUTH_BY_DEVICE_TYPE,deviceTypeId,null,null,order.getEnterpriseId());

            System.out.println("ruleForDepartment:"+ruleForDepartment);

            System.out.println("ruleForFailType:"+ruleForFailType);

            System.out.println("ruleForDeviceType:"+ruleForDeviceType);

            Date date = new Date();

            List<String> list = new ArrayList<>();
            if("0".equals(conditionStatus)){
                OsmDispatchRelaStaff rela = new OsmDispatchRelaStaff();
                for(DispatchRule rule:ruleForDepartment){
                    rela.setId(UuidUtil.getRandomUuid());
                    rela.setCreateTime(date);
                    rela.setUpdateTime(date);
                    rela.setOrderId(orderId);
                    rela.setStaffId(rule.getMan_id());
                    rela.setStatus(new Byte("1"));
                    osmDispatchRelaStaffMapper.insertSelective(rela);
                    String content = "收到新工单【"+order.getOrderTitle() +"】，快去抢单吧";
                    JsonObject jsonObject = new JsonObject();
                    jsonObject.addProperty("order_type","1");
                    jsonObject.addProperty("type","1");
                    jsonObject.addProperty("order_id",order.getId());
                    String extra = GsonUtil.toJson(jsonObject);
                    String title = "收到可抢单工单";
                    CreateNotifyReq createNotifyReq = new CreateNotifyReq(content,extra,title,"",rela.getStaffId(),order.getEnterpriseId());
                    notifyUtil.send(createNotifyReq);
                    list.add(rule.getMan_id());

                }
                for(DispatchRule rule:ruleForFailType){
                    if(list.contains(rule.getMan_id())){
                        continue;
                    }else {
                        list.add(rule.getMan_id());
                    }
                    rela.setId(UuidUtil.getRandomUuid());
                    rela.setCreateTime(date);
                    rela.setUpdateTime(date);
                    rela.setOrderId(orderId);
                    rela.setStaffId(rule.getMan_id());
                    rela.setStatus(new Byte("1"));
                    osmDispatchRelaStaffMapper.insertSelective(rela);

                    String content = "收到新工单【"+order.getOrderTitle() +"】，快去抢单吧";
                    JsonObject jsonObject = new JsonObject();
                    jsonObject.addProperty("order_type","1");
                    jsonObject.addProperty("type","1");
                    jsonObject.addProperty("order_id",order.getId());
                    String extra = GsonUtil.toJson(jsonObject);
                    String title = "收到可抢单工单";
                    CreateNotifyReq createNotifyReq = new CreateNotifyReq(content,extra,title,"",rela.getStaffId(),order.getEnterpriseId());
                    notifyUtil.send(createNotifyReq);

                }
                for(DispatchRule rule:ruleForDeviceType){
                    if(list.contains(rule.getMan_id())){
                        continue;
                    }else {
                        list.add(rule.getMan_id());
                    }
                    rela.setId(UuidUtil.getRandomUuid());
                    rela.setCreateTime(date);
                    rela.setUpdateTime(date);
                    rela.setOrderId(orderId);
                    rela.setStaffId(rule.getMan_id());
                    rela.setStatus(new Byte("1"));
                    osmDispatchRelaStaffMapper.insertSelective(rela);

                    String content = "收到新工单【"+order.getOrderTitle() +"】，快去抢单吧";
                    JsonObject jsonObject = new JsonObject();
                    jsonObject.addProperty("order_type","1");
                    jsonObject.addProperty("type","1");
                    jsonObject.addProperty("order_id",order.getId());
                    String extra = GsonUtil.toJson(jsonObject);
                    String title = "收到可抢单工单";
                    CreateNotifyReq createNotifyReq = new CreateNotifyReq(content,extra,title,"",rela.getStaffId(),order.getEnterpriseId());
                    notifyUtil.send(createNotifyReq);

                }
                if(list.isEmpty()){
                    order.setStatus("3");
                    order.setIsAutoCatch(0);
                }else {
                    order.setDispatchTime(new Date());
                    order.setStatus("4");
                    order.setIsAutoCatch(1);
                }
            }else {
                List<String> staffIdList = new ArrayList();
                String objIds = "";
                objIds = order.getFailTypeId();
                if(!StringUtils.isEmpty(order.getDeviceTypeId())){
                    objIds += ","+order.getDeviceTypeId();
                }
                if(!StringUtils.isEmpty(order.getDepartmentId())){
                    objIds += ","+order.getDepartmentId();
                }
                staffIdList = osmDispatchRuleMapper.queryStaffId(objIds,order.getEnterpriseId());
                if(staffIdList.isEmpty()){
                    order.setStatus("3");
                    order.setIsAutoCatch(0);
                }
                for(String staffId:staffIdList){
                    OsmDispatchRelaStaff rela = new OsmDispatchRelaStaff();
                    rela.setId(UuidUtil.getRandomUuid());
                    rela.setCreateTime(date);
                    rela.setUpdateTime(date);
                    rela.setOrderId(orderId);
                    rela.setStaffId(staffId);
                    rela.setStatus(new Byte("1"));
                    osmDispatchRelaStaffMapper.insertSelective(rela);

                    String content = "收到新工单【"+order.getOrderTitle() +"】，快去抢单吧";
                    JsonObject jsonObject = new JsonObject();
                    jsonObject.addProperty("order_type","1");
                    jsonObject.addProperty("type","1");
                    jsonObject.addProperty("order_id",order.getId());
                    String extra = GsonUtil.toJson(jsonObject);
                    String title = "收到可抢单工单";
                    CreateNotifyReq createNotifyReq = new CreateNotifyReq(content,extra,title,"",rela.getStaffId(),order.getEnterpriseId());
                    notifyUtil.send(createNotifyReq);
                }
            }

        }else {
            order.setStatus("3");
            order.setIsAutoCatch(0);
        }

        osmOrderFailureMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public RspRulePage findPage(String enterpriseId,String type, String objId, String authMan, String authObjName,Integer pageNum,Integer pageSize) {
        RspRulePage rspRulePage = new RspRulePage();
        Page page = PageHelper.startPage(pageNum,pageSize,true);
        List<DispatchRule> list = osmDispatchRuleMapper.getDispatchesByCond(type,objId,authMan,authObjName,enterpriseId);
        rspRulePage.setData_list(list);
        rspRulePage.setPage_num(page.getPageNum());
        rspRulePage.setTotal_num(page.getTotal());
        rspRulePage.setPage_size(pageSize);
        return rspRulePage;
    }
}
